import { defineStore } from "pinia";
import { defaultErrorHandler } from "../utils/default-error-handler";
import { ref } from "vue";
import { chatGptApi } from "../api/api";
import { Message } from "./types";

export const useCounterStore = defineStore("counter", () => {
  const count = ref(0);
  const messageList = ref<Array<Partial<Message>>>([]);

  function increment() {
    count.value++;
  }

  async function fetch(message: string) {
    try {
      messageList.value.push({
        text: message,
        type: "request",
      });

      const res = (await chatGptApi(message)) as Partial<Message>;

      if (res.statusCode) {
        defaultErrorHandler(res.statusText);
      } else {
        messageList.value.push({
          ...res,
          type: "response",
        });
      }
    } catch (error) {
      defaultErrorHandler(error);
    }
  }

  // function

  return { count, increment, fetch, messageList };
});
